package com.zhongyu.provider.service;

import com.zhongyu.comm.api.DetailApi;
import com.zhongyu.comm.vo.DetailVo;
import com.zhongyu.provider.mapper.DetailMapper;
import com.zhongyu.provider.pojo.Detail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class DetailApiImpl implements DetailApi {

    @Resource
    private DetailMapper detailMapper;

    @Value("${spring.application.name}")
    private String serviceId;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    /**
     * 查到是一个实体类 方法要求返回的是vo对象  vo和实体类是属性是一一对应
     *所以要进行转换  list.stream.map 取出detail
     *然后得到vo对象  然后把detail复制给vo
     * 再转换成list
     * @return
     */
    @Override
    public List<DetailVo> searchAll() {
        ServiceInstance serviceInstance = loadBalancerClient.choose(serviceId);
        log.debug("当前调用的是eureka-client提供者服务Id为:"+serviceId);
        log.debug("IP为: "+serviceInstance.getHost());
        log.debug("端口号为: "+serviceInstance.getPort());
        log.debug("URL为:"+serviceInstance.getUri());
        List<Detail> list = detailMapper.selectList(null);
        return list.stream().map(detail -> {
            DetailVo vo = new DetailVo();
            BeanUtils.copyProperties(detail,vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public int del(int id) {
        return detailMapper.deleteById(id);
    }
}
